<template>
	<view class="container">
		<!-- 联系人 -->
		<view class="form-item">
			<text class="label">联系人</text>
			<input class="input" v-model="form.contactName" placeholder="请输入姓名" />
		</view>

		<!-- 联系电话 -->
		<view class="form-item">
			<text class="label">联系电话</text>
			<input class="input" v-model="form.contactPhone" placeholder="请输入联系电话" type="number" />
		</view>

		<!-- 详细地址 -->
		<view class="form-item">
			<text class="label">详细地址</text>
			<input class="input" v-model="form.address" placeholder="请输入详细地址" />
		</view>

		<!-- 地图位置 -->
		<view class="form-item">
			<text class="label">地图位置</text>
			<map 
				style="width: 100%; height: 300rpx;" 
			/>
			<button class="map-button" @click="selectLocation">选择位置</button>
		</view>

		<!-- 保存按钮 -->
		<button class="submit-button" @click="saveDelivery">保存配送信息</button>
	</view>
</template>

<script>
import { updateDelivery } from "../../../api/delivery/delivery.js";

export default {
	data() {
		return {
			form: {
				contactName: "",
				contactPhone: "",
				address: "",
				deliveryId: null, // 当前记录的 ID，用于编辑时使用
			},
		};
	},
	onLoad(options) {
		// 检查是否有编辑数据传入
		if (options.delivery) {
			try {
				this.form = JSON.parse(decodeURIComponent(options.delivery));
			} catch (error) {
				console.error("配送信息解析失败:", error);
				uni.showToast({ title: "数据解析失败", icon: "none" });
			}
		}
	},
	methods: {
		// 选择地图位置
		selectLocation() {
	
					uni.showToast({ title: "定位失败，请重试", icon: "error" });
			
		},
		// 保存配送信息
		async saveDelivery() {
			// 表单校验
			if (!this.form.contactName.trim()) {
				uni.showToast({ title: "请输入联系人姓名", icon: "error" });
				return;
			}
			if (!this.form.contactPhone.trim() || !/^1[3-9]\d{9}$/.test(this.form.contactPhone)) {
				uni.showToast({ title: "请输入有效的联系电话", icon: "error" });
				return;
			}
			if (!this.form.address.trim()) {
				uni.showToast({ title: "请输入详细地址", icon: "error" });
				return;
			}

			// 准备请求数据
			const deliveryData = {
				contactName: this.form.contactName,
				contactPhone: this.form.contactPhone,
				address: this.form.address,
				deliveryId: this.form.deliveryId,
			};

			// 调用保存接口
			try {
				await updateDelivery(deliveryData);
				uni.showToast({ title: "保存成功", icon: "success" });

				// 延时返回上一页
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			} catch (err) {
				console.error("保存失败:", err);
				uni.showToast({ title: "保存失败，请重试", icon: "error" });
			}
		},
	},
};
</script>

<style scoped>
.container {
	padding: 20px;
}
.form-item {
	margin-bottom: 20px;
}
.label {
	display: block;
	margin-bottom: 5px;
	font-size: 16px;
	color: #333;
}
.input {
	text-align: left;
	width: 100%;
	border: 1px solid #ccc;
	border-radius: 5px;
	font-size: 14px;
}
.map-button,
.submit-button {
	width: 100%;
	padding: 10px;
	background-color: #007aff;
	color: white;
	text-align: center;
	border: none;
	border-radius: 5px;
	font-size: 16px;
	margin-top: 20px;
}
.map-button {
	background-color: #34c759;
}
</style>
